<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>5_getSnapshotBeforeUpdate使用场景</title>
  <style>
    .list{
      width: 450px;
      height: 400px;
      border-radius: 3%;
      background-color: #0984e3;
      overflow: auto;
    }
    .news{
      height: 80px;
      text-align: center;
    }
  </style>
</head>
<body>
  <!-- 准备一个容器 -->
  <div id="test"></div>

  <!-- 引入react核心插件 -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- 操作DOM插件 -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- jsx转js插件 -->
  <script type="text/javascript" src="../js/babel.min.js"></script>


  <script type="text/babel">
    /*
    1.初始化阶段:由ReactDOM.render()触发 --- 初次渲染
        1. constructor()
        2. **getDerivedStateFromProps()**
        3. render()
        4. componentDidMount()
    2.更新阶段: 由组件内部this.setSate()或父组件重新 render 触发
        1. **getDerivedStateFromProps()**
        2. shouldComponentUpdate()
        3. render()
        4. **getSnapshotBeforeUpdate()**
        5. componentDidUpdate()
    3.卸载组件:由 ReactDOMunmountComponentAtNode()触发
        1.componentWillUnmount()
    */
    // 创建组件
    class LookNews extends React.Component{
      // 初始化状态
      state = {
        newsArr:[]
      }

      // 挂在完成后钩子
      componentDidMount(){
        // 定时器
        setInterval(()=>{
        // 获取初始状态
        const {newsArr} = this.state
        // 事件：模拟一条新闻
        const news = `新闻${newsArr.length+1}`
        // 更新状态
        this.setState({newsArr:[news,...newsArr]})
        }, 1000)
      }

      // 更新之前的快照钩子
      getSnapshotBeforeUpdate(){
        return this.refs.list.scrollHeight
      }

      // 更新完成钩子
      componentDidUpdate(prevState, prevProps, height){
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height 
      }

      render(){
        return(
          <div className="list" ref="list">
            {
              this.state.newsArr.map((n, index)=>{
                return (
                  <div key={index} className="news">{n}</div>
                )
              })
            }
          </div>
        )
      }
    }


    // 渲染组件到页面
    const container = document.getElementById('test')
    const root = ReactDOM.createRoot(container)
    root.render(<LookNews/>)
  </script>

</body>
</html>